package com.item.mall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.item.mall.entity.Orders;
import com.item.mall.entity.User;
import com.item.mall.mapper.OrderMapper;
import com.item.mall.mapper.UserAddressMapper;
import com.item.mall.service.OrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.item.mall.service.UserAddressService;
import com.item.mall.vo.OrderDetailVO;
import com.item.mall.vo.OrderVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 张津瑞、彭家博
 * @since 2021-07-31
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Orders> implements OrderService {
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    UserAddressService userAddressService;


    @Override
    public Orders saveOrder(Integer userId, Orders orders) {
        if(orders.getAddressId()==-1){
            orders.setAddressId(userAddressService.getDefaultAddress(userId).getId());
        }

        orders.setUserId(userId);
        //生成并存入订单号
        String serialnumber = null;
        try {
            StringBuffer result = new StringBuffer();
            for(int i=0;i<32;i++) {
                result.append(Integer.toHexString(new Random().nextInt(16)));
            }
            serialnumber =  result.toString().toUpperCase();
        } catch (Exception e) {
            e.printStackTrace();
        }
        orders.setSerialnumber(serialnumber);
        orderMapper.insert(orders);
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("serialnumber",serialnumber);
        return orderMapper.selectOne(queryWrapper);
    }

    @Override
    public List<OrderVO> getOrderVOList() {
        List<Orders> ordersList = orderMapper.selectList(null);
        List<OrderVO> orderVOList=new ArrayList<>();
        for (Orders orders : ordersList) {
            OrderVO orderVO =new OrderVO();
            orderVO.setSerialnumber(orders.getSerialnumber());
//            orderVO.setUserAddress(orders.getUserAddress());
            orderVO.setTotalCost(orders.getCost());
            orderVO.setOrderDetailVOList(orderMapper.getOrderDetailVO(orders.getId()));
            orderVOList.add(orderVO);
        }

        return orderVOList;
    }
}
